<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span class="title">新增验收标准</span>
        <div class="btn-wrap">
          <el-button
            v-if="showBtn('高级关联')"
            size="middle"
            type="text"
            @click="handleSeniorLinked"
            >高级关联</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button
            v-if="showBtn('关联商品')"
            size="middle"
            type="text"
            @click="handleAssociateProduct"
            >关联商品</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-button
            size="middle"
            type="text"
            :loading="exportLoading"
            @click="handleExportFile"
            >模板导出</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <el-upload
            class="import-file"
            ref="bacthUpload"
            :action="`${uploadBaseURL}sysback/checkStandardAdd/importExcel`"
            accept=".xls, .xlsx"
            :before-upload="beforeFileUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :show-file-list="false"
          >
            <el-button size="middle" type="text" :loading="importBtnLoading"
              >模板导入</el-button
            >
          </el-upload>
          <el-divider direction="vertical"></el-divider>
          <el-button
            size="middle"
            type="text"
            :loading="saveBtnLoading"
            @click="handleSave"
            >提交</el-button
          >
        </div>
      </div>
      <div>
        <Umy-table
          :loading="tableLoading"
          :data-source="baseTableData"
          :columns="tableColumns"
          :isShowSortNum="true"
          :tableHeight="600"
          @handleCancelSelect="handleCancelSelect"
        />
      </div>
    </el-card>
    <associate-product-dialog
      ref="associateDialog"
      :dialogVisible="dialogVisible"
      @query-data="handleQueryTableData"
      @hide-handler="handleCloseDialog"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
  </div>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import UmyTable from '@/components/UmyTable';
import AssociateProductDialog from '../components/AssociateProduct';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import { isResponseSuccess, setAuthBtnId } from '@/utils/bizUtils';
import { mapGetters } from 'vuex';

export default {
  mixins: [],
  components: {
    UmyTable,
    AssociateProductDialog,
    SeniorLinkedDialog
  },
  data () {
    return {
      skuNos: [],
      dialogVisible: false,
      exportLoading: false,
      importBtnLoading: false,
      tableLoading: false,
      saveBtnLoading: false,
      baseTableData: [], // 列表的数据源
      tableColumns: [],
      apiObj: {
        // 查询基本信息
        queryCheckStandardInfo: {
          url: ' /sysback/checkStandardAdd/getAddedSkuSdList',
          type: 'post'
        },
        // 提交
        commitBasicInfo: {
          url: '/sysback/checkStandardAdd/commit',
          type: 'post'
        },
        // 导出
        exportApi: {
          url: '/sysback/checkStandardAdd/exportExcel',
          type: 'post'
        }
      },
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }],
        isSenior: false
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn'])
  },
  created () {
    this.initTabaleClonum();
  },
  methods: {
    initTabaleClonum () {
      this.tableColumns = [
        {
          title: '品类',
          align: 'center',
          key: 'categoryPath'
        },
        {
          title: 'SPU编码',
          align: 'center',
          key: 'spuNo',
          width: 90
        },
        {
          title: 'SKU编码',
          align: 'center',
          key: 'skuNo',
          width: 90
        },
        {
          title: '商品名称',
          align: 'center',
          key: 'productName'
        },
        {
          title: '规格',
          align: 'center',
          key: 'specDetail'
        },
        {
          title: '品牌',
          align: 'center',
          key: 'brandName'
        },
        {
          title: '验收时间',
          align: 'center',
          key: 'checkTime',
          required: true,
          type: 'select',
          options: [
            {
              value: '入库前',
              label: '入库前'
            },
            {
              value: '入库后',
              label: '入库后'
            }
          ]
        },
        {
          title: '验收频率',
          align: 'center',
          key: 'checkFrequency',
          required: true,
          type: 'inputNumPrecision',
          precision: 0,
          minVal: 1,
          width: 150
        }
      ];
    },
    handleQueryTableData (skuList) {
      let skuNoList = this.skuNos.concat(skuList);
      this.baseTableData = [];
      const isNullSkuNos = (skuNoList ?? []).filter(item => item).length == 0
      if (isNullSkuNos) return
      this.tableColumns = [];
      // 开始请求列表
      this.tableLoading = true;
      ApiRequest(
        this.apiObj.queryCheckStandardInfo.url,
        this.apiObj.queryCheckStandardInfo.type,
        { skuNos: [...new Set(skuNoList)] },
        false
      )
        .then((res) => {
          this.tableLoading = false;
          if (isResponseSuccess(res)) {
            this.skuNos = [...new Set(skuNoList)];
            let reData = res.retData;
            this.handleFormatTableData(reData);
          } else {
            this.initTabaleClonum();
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    handleFormatTableData (reData) {
      this.baseTableData = [];
      this.tableColumns = [];
      this.initTabaleClonum();
      reData.forEach((element, oneIndex) => {
        // 准备一行数据的普通列
        let curRow = {
          productName: element.productName,
          brandName: element.brandName,
          categoryPath: element.categoryPath,
          categoryUuid: element.categoryUuid,
          spuNo: element.spuNo,
          skuNo: element.skuNo,
          checkTime: element.checkTime,
          specDetail: element.specDetail,
          checkFrequency: element.checkFrequency,
          detailList: element.detailList
        };
        // 新建表头。并准备一行数据的动态列
        element.detailList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        // 将行，添加到展示列表
        this.baseTableData.push(curRow);
      });
      this.tableColumns.push({
        title: '操作',
        key: 'action',
        align: 'center',
        fixed: 'right',
        width: 90
      });
    },
    pushItem (oneIndex, curRow, innerEle, index) {
      // 将行内动态列的信息，平铺到行
      curRow['checkCount' + index] = innerEle.checkCount;
      curRow['standardValue' + index] = innerEle.standardValue;
      curRow['upDiffValue' + index] = innerEle.upDiffValue;
      curRow['downDiffValue' + index] = innerEle.downDiffValue;
      curRow['checkMethod' + index] = innerEle.checkMethod;
      curRow['checkItemType' + index] = innerEle.checkItemType; // 1数字5个列可填，2文本3个列可填

      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        if (innerEle.checkItemType !== '2') {
          this.tableColumns.push({
            title: innerEle.checkItemName,
            required: innerEle.isNeed === '1',
            key: innerEle.checkItemUuid,
            width: 150,
            align: 'center',
            children: [
              {
                title: '验收次数',
                align: 'center',
                key: 'checkCount' + index,
                type: 'inputNumPrecision',
                minVal: 1,
                maxVal: 5,
                width: 160
              },
              {
                title: '标准值',
                align: 'center',
                key: 'standardValue' + index,
                type: 'input',
                width: 150
              },
              {
                title: '上差值',
                align: 'center',
                key: 'upDiffValue' + index,
                type: 'inputNum',
                width: 160
              },
              {
                title: '下差值',
                align: 'center',
                key: 'downDiffValue' + index,
                type: 'inputNum',
                width: 160
              },
              {
                title: '验收方法',
                align: 'center',
                key: 'checkMethod' + index,
                type: 'input',
                width: 150
              }
            ]
          });
        } else {
          this.tableColumns.push({
            title: innerEle.checkItemName,
            required: innerEle.isNeed === '1',
            key: innerEle.checkItemUuid,
            width: 150,
            align: 'center',
            children: [
              {
                title: '验收次数',
                align: 'center',
                key: 'checkCount' + index,
                type: 'inputNumPrecision',
                minVal: 1,
                maxVal: 5,
                width: 160
              },
              {
                title: '标准值',
                align: 'center',
                key: 'standardValue' + index,
                type: 'input',
                width: 150
              },
              {
                title: '验收方法',
                align: 'center',
                key: 'checkMethod' + index,
                type: 'input',
                width: 150
              }
            ]
          });
        }
      }
    },
    // 格式化提交数据
    formatSubmitData () {
      let submitList = [];
      this.baseTableData.forEach((element) => {
        element.detailList.forEach((item, innerI) => {
          item.checkCount = element['checkCount' + innerI];
          item.standardValue = element['standardValue' + innerI];
          item.upDiffValue = element['upDiffValue' + innerI];
          item.downDiffValue = element['downDiffValue' + innerI];
          item.checkMethod = element['checkMethod' + innerI];
        });
        submitList.push({
          brandName: element.brandName,
          categoryPath: element.categoryPath,
          categoryUuid: element.categoryUuid,
          checkFrequency: element.checkFrequency,
          checkTime: element.checkTime,
          productName: element.productName,
          specDetail: element.specDetail,
          skuNo: element.skuNo,
          spuNo: element.spuNo,
          detailList: element.detailList
        });
      });
      return submitList;
    },
    // 保存
    handleSave () {
      this.saveBtnLoading = true;
      ApiRequest(
        this.apiObj.commitBasicInfo.url,
        this.apiObj.commitBasicInfo.type,
        { commitList: this.formatSubmitData() },
        false
      )
        .then((res) => {
          if (res.retStatus === '1') {
            this.$Message.success('提交成功');
            this.$router.go(-1);
          }
          this.saveBtnLoading = false;
        })
        .catch(() => {
          this.saveBtnLoading = false;
        });
    },
    beforeFileUpload (file) {
      this.baseTableData = [];
      this.tableLoading = true;
      this.importBtnLoading = true;
    },
    uploadSuccess (res) {
      this.tableLoading = false;
      this.importBtnLoading = false;
      if (isResponseSuccess(res)) {
        this.skuNos = res.retData.map((item) => {
          return item.skuNo;
        });
        let reData = res.retData;
        this.handleFormatTableData(reData);
      } else {
        this.$message.error(res.retMessage || '模板导入异常');
      }
    },
    uploadError (file) {
      this.tableLoading = false;
      this.importBtnLoading = false;
      this.$message.error('模板导入异常');
    },
    handleAssociateProduct () {
      console.log('关联商品');
      this.$refs.associateDialog.handleEmptySkus();
      this.dialogVisible = true;
    },
    handleCloseDialog (skuList) {
      this.dialogVisible = false;
      this.getGoodsResultFn(skuList);
    },
    // 删除
    handleCancelSelect (obj) {
      const { index, row } = obj;
      // this.baseTableData.splice(index, 1);
      this.baseTableData = this.baseTableData.filter((item, i) => i != index);
      this.skuNos = this.skuNos.filter((item) => item != row.skuNo);
    },
    // 模板导出
    handleExportFile () {
      if (this.baseTableData.length === 0) {
        return this.$Message.warning('请先关联商品');
      }
      this.exportLoading = true;
      ApiRequestExportTable(
        this.apiObj.exportApi.url,
        this.apiObj.exportApi.type,
        { exportList: this.formatSubmitData() },
        false
      )
        .then((res) => {
          this.exportLoading = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '新增验收标准模板.xls';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    // 高级关联
    handleSeniorLinked () {
      setAuthBtnId('高级关联');
      this.seniorLinked.visible = true;
    },
    // 获取高级关联结果
    getSeniorResultFn (skuNos) {
      if (!this.seniorLinked.isSenior) {
        this.skuNos = [];
      }
      this.seniorLinked.isSenior = true;
      this.handleQueryTableData(skuNos);
    },
    // 获取关联商品结果
    getGoodsResultFn (skuNoList) {
      if (this.seniorLinked.isSenior) {
        this.skuNos = [];
      }
      this.seniorLinked.isSenior = false;
      this.handleQueryTableData(skuNoList);
    }
  }
};
</script>
<style lang="less" scoped>
.btn-wrap {
  float: right;
  .import-file {
    display: inline;
  }
}
.card-header {
  .title {
    font-size: 16px;
  }
}
</style>
